package com.faxsun.web.processor;

import java.util.Currency;
import java.util.Locale;
import java.util.Map;

import org.apache.commons.collections.map.HashedMap;
import org.broadleafcommerce.common.money.Money;
import org.thymeleaf.Arguments;
import org.thymeleaf.dom.Element;
import org.thymeleaf.processor.attr.AbstractTextChildModifierAttrProcessor;
import org.thymeleaf.standard.expression.Expression;
import org.thymeleaf.standard.expression.StandardExpressions;

public class PriceTextDisplayProcessor extends
		AbstractTextChildModifierAttrProcessor {

	@SuppressWarnings("unchecked")
	private final static Map<Currency, Locale> CURRENCY_LOCALE = new HashedMap();

	static {
		CURRENCY_LOCALE.put(Currency.getInstance(Locale.CHINA), Locale.CHINA);
//		CURRENCY_LOCALE.put(Currency.getInstance(Locale.UK), Locale.UK);
//		CURRENCY_LOCALE.put(Currency.getInstance(Locale.US), Locale.US);
//		CURRENCY_LOCALE.put(Currency.getInstance(Locale.GERMANY), Locale.GERMANY);
//		CURRENCY_LOCALE.put(Currency.getInstance(Locale.FRANCE), Locale.FRANCE);
//		CURRENCY_LOCALE.put(Currency.getInstance(Locale.CANADA), Locale.CANADA);
//		Locale newzland=new Locale("en", "NZ");
//		CURRENCY_LOCALE.put(Currency.getInstance(newzland), newzland);
	}

	/**
	 * Sets the name of this processor to be used in Thymeleaf template
	 */
	public PriceTextDisplayProcessor() {
		super("fsprice");
	}

	@Override
	public int getPrecedence() {
		return 1300;
	}

	@Override
	protected String getText(Arguments arguments, Element element,
			String attributeName) {

		Money price = null;
		String text = null;
		Expression expression = (Expression) StandardExpressions
				.getExpressionParser(arguments.getConfiguration())
				.parseExpression(arguments.getConfiguration(), arguments,
						element.getAttributeValue(attributeName));
		Object result = expression.execute(arguments.getConfiguration(),
				arguments);
		if (result instanceof Money) {
			price = (Money) result;
		} else if (result instanceof Number) {
			price = new Money(((Number) result).doubleValue());
		}

		if (price == null) {
			text = "";
		} else {
			Currency currency = price.getCurrency();
			StringBuffer sb = new StringBuffer();
			Locale locale = CURRENCY_LOCALE.get(currency);
			if (locale != null) {
				sb.append(currency.getSymbol(locale));
			} else {
				sb.append(currency.getCurrencyCode());
			}
			sb.append(" ");
			sb.append(price.getAmount().toString());
//			sb.append(" ");
//			sb.append(currency.getDisplayName());
			text = sb.toString();
		}

		return text;
	}
}
